package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.form.cart.CheckItemAllForm;
import com.cskaoyan.gateway.form.cart.UpdateCartForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: cs-mall_35th
 * @description: 商品模块之购物车
 * @author: Weiwei Liu
 * @create: 2021-12-11 19:33
 **/
@Slf4j
@RestController
@RequestMapping("/shopping")
public class CartsController {

    @Reference(timeout = 3000, retries = 0, check = false)
    ICartService cartService;


    // 获得购物车列表
    @GetMapping("carts")
    public ResponseData getCartsByGet(CartListByIdRequest request, HttpServletRequest httpServletRequest) {

        // 获取用户id
        long uid = getUid(httpServletRequest);

        request.setUserId(uid);

        CartListByIdResponse cartListByIdResponse = cartService.getCartListById(request);

        if (cartListByIdResponse.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(cartListByIdResponse.getCartProductDtos());

        }
        return new ResponseUtil<>().setErrorMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
    }


    private Long getUid(HttpServletRequest httpServletRequest) {
        //拿到用户id
        String userInfo = (String) httpServletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject jsonObject = JSON.parseObject(userInfo);
        return Long.parseLong(jsonObject.get("id").toString());
    }


    // 添加商品到购物车
    @PostMapping("carts")
    public ResponseData getCartsByPost(@RequestBody AddCartRequest request){
        AddCartResponse response = cartService.addToCart(request);

        if(ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setData("成功");

        }
        return new ResponseUtil<>().setErrorMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
    }





    // 更新购物车中的商品
    @PutMapping("carts")
    public ResponseData cartsUpdate(@RequestBody UpdateCartForm form, HttpServletRequest httpServletRequest){

        UpdateCartNumRequest request = new UpdateCartNumRequest();

        Long uid = getUid(httpServletRequest);

        if (uid != form.getUserId()) {
            log.info("前端用户id:" + form.getUserId() + "servletRequest内部的用户id：" + uid);
            return new ResponseUtil<>().setErrorMsg("用户id不一致,请检查");
        }


        request.setUserId(form.getUserId());
        request.setItemId(form.getProductId());
        request.setNum(form.getProductNum());
        request.setChecked(form.getChecked());
        UpdateCartNumResponse response = cartService.updateCartNum(request);


        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }





    // 删除购物车中的商品
    @DeleteMapping("/carts/{uid}/{pid}")
    public ResponseData deleteCart(@PathVariable("uid") Long uid,@PathVariable("pid") Long pid, HttpServletRequest httpServletRequest){


        DeleteCartItemRequest request = new DeleteCartItemRequest();

        Long userId = getUid(httpServletRequest);


        if (uid != userId) {
            log.info("前端用户id:" + uid + "servletRequest里的用户id：" + userId);
            return new ResponseUtil<>().setErrorMsg("用户id不一致！");
        }


        request.setUserId(uid);
        request.setItemId(pid);
        DeleteCartItemResponse response = cartService.deleteCartItem(request);


        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }





    // 删除购物车选中的商品
    @DeleteMapping("/items/{id}")
    public ResponseData deleteCheckedItem(@PathVariable("id")Long id,HttpServletRequest httpServletRequest){

        DeleteCheckedItemRequest request = new DeleteCheckedItemRequest();

        Long userId = getUid(httpServletRequest);

        if(!userId.equals(userId)){
            log.info("前端用户id:"+id+"servletRequest里的用户id："+userId);
            return new ResponseUtil<>().setErrorMsg("用户id不一致！");
        }
        request.setUserId(id);
        DeleteCheckedItemResposne response = cartService.deleteCheckedItem(request);


        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }





    // 全选/全不选购物车商品
    @PutMapping("/items")
    public ResponseData checkAllItems(@RequestBody CheckItemAllForm form, HttpServletRequest servletRequest){

        CheckAllItemRequest request = new CheckAllItemRequest();

        Long userId = form.getUserId();

        String checked = form.getChecked();

        request.setUserId(userId);
        request.setChecked(checked);
        CheckAllItemResponse response = cartService.checkAllCartItem(request);

        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getMsg());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


}
